#! /bin/sh

get_path()
{
	pushd $1 &> /dev/null
	abspath=`pwd`
	lastnode=`basename "$abspath"`
	popd &> /dev/null
}

show_help()
{
	echo "$0 <instance name> <working directory> [<command>]"
	exit 1
}


# main
if [ $# -ne 2 -a $# -ne 3 ]; then
	show_help
fi

get_path $2

shell_title="$1://$lastnode/"
init_script="cd $abspath; clear"
shell_script=""

if [ "$3" != "" ]; then
	shell_script="$3"
fi

osascript <<SCRIPT
set theTitle to "$shell_title"
set newTerm to true

tell application "Terminal"
	if it is not running then
		launch
	end if

	repeat with win in every window
		if theTitle is in (custom title of win as string) then
			activate
			set theTerm to win
			set newTerm to false
			exit repeat
		end if
	end repeat

	-- open new window
	if newTerm then
		tell application "System Events"
			set frontmost of process "Terminal" to true
			keystroke "n" using command down
		end tell
		set custom title of the first window to theTitle
		set theTerm to the first window
	end if

	-- position
	tell application "Finder"
		set desktopSize to bounds of window of desktop
	end tell
	set winSize to get the bounds of theTerm
	set winPos to { 0, 0 }
	set item 1 of winPos to ((item 3 of desktopSize) / 2) - (((item 3 of winSize) - (item 1 of winSize))/ 2)
	set item 2 of winPos to ((item 4 of desktopSize) / 2) - (((item 4 of winSize) - (item 2 of winSize))/ 2)

	set position of theTerm to winPos

	-- execute script
	if "$shell_script" is not equal to "" then
		do script "$init_script" in theTerm
		do script "$shell_script" in theTerm
	else if newTerm then
		do script "$init_script" in theTerm
	end if

end tell
SCRIPT

